package ru.ifmo.ctddev.krotkov.helloudp;

import java.io.*;
import java.net.*;
import java.util.Scanner;

public class Sender implements Runnable {

	DatagramSocket socket;
	int num, myPort, destinationPort;
	String target;

	@Override
	public void run() {
		
		for (int i = 0; i < 10; i++) {
			ByteArrayOutputStream bios = new ByteArrayOutputStream();
			PrintWriter out = new PrintWriter(bios);
			
			out.println("query #" + i + " from thread #" + num);
			out.flush();
			try {
				socket.send(new DatagramPacket(bios.toByteArray(), bios.size(), Inet4Address.getByName(target), destinationPort));
				//bios.flush();
				byte[] buf = new byte[100];
				DatagramPacket ans = new DatagramPacket(buf, 100);
				socket.receive(ans);
				Scanner in = new Scanner( new ByteArrayInputStream(ans.getData()));
				String answer = in.nextLine();
				System.out.println(answer);
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

	}

	public Sender(int num, int myPort, String target, int destinationPort) {
		super();
		this.num = num;
		this.myPort = myPort;
		this.destinationPort = destinationPort;
		this.target = target;
		try {
			try {
				socket = new DatagramSocket(myPort, Inet4Address.getByName("localhost"));
				
			} catch (UnknownHostException e) {
				e.printStackTrace();
			}
		} catch (SocketException e) {
			e.printStackTrace();
		}
	}

}
